<?php

namespace addons\qingdong\controller;

use addons\qingdong\model\Contract as ContractModel;
use addons\qingdong\model\Event;
use addons\qingdong\model\ExamineRecord;
use addons\qingdong\model\Feedback;
use addons\qingdong\model\ReceivablesPlan;
use addons\qingdong\model\Customer;
use addons\qingdong\model\Contacts;
use addons\qingdong\model\Contract;
use addons\qingdong\model\Leads;
use addons\qingdong\model\Receivables;
use addons\qingdong\model\Staff;
use addons\qingdong\model\Record;
use addons\qingdong\model\Message;
use addons\qingdong\model\Business;

/**
 *  * 操作文档：https://doc.fastadmin.net/qingdong
 * 软件介绍：https://www.fastadmin.net/store/qingdong.html
 * 售后微信：qingdong_crm
 * 首页接口
 */
class Index extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $this->error("当前插件暂无前台页面");
    }

    //搜索
    public function search()
    {
        $keywords = input('keywords');
        $type = input('type');
        if (empty($keywords)) {
            $this->error('筛选字段不能为空');
        }
        //客户
        $customer = Customer::where([
            'name' => ['like', "%$keywords%"],
            'owner_staff_id' => ['in', Staff::getMyStaffIds()],
        ])->with([
            'ownerStaff',
            'contacts'
        ])->field('id,name,next_time,owner_staff_id,level,follow')->select();
        //联系人
        $contacts = Contacts::where([
            'name' => ['like', "%$keywords%"],
            'owner_staff_id' => ['in', Staff::getMyStaffIds()],
        ])->with(['customer'])->field('id,name,mobile,customer_id')->select();
        //线索
        $leads = Leads::where([
            'name' => ['like', "%$keywords%"],
            'owner_staff_id' => ['in', Staff::getMyStaffIds()],
        ])->with(['ownerStaff'])->field('id,owner_staff_id,name,follow,level,next_time,mobile')->select();

        $this->success('请求成功', [
            'customer' => $customer,
            'contacts' => $contacts,
            'leads' => $leads
        ]);
    }


    //反馈
    public function feedback()
    {
        $content = input('content', '', 'trim');
        $file = input('file', '', 'trim');
        if (empty($content)) {
            $this->error('请输入反馈内容！');
        }
        $model = new Feedback();
        $model->save([
            'staff_id' => $this->auth->id,
            'content' => $content,
            'file_ids' => $file
        ]);
        $this->success('反馈成功');
    }


    //待办事项
    public function agent()
    {
        $where['create_staff_id'] = $this->auth->id;
        $where['next_time'] = array(array('egt', date('Y-m-d 00:00:00')), array('lt', date('Y-m-d 23:59:59')));
        $where['follow_type'] = ['neq', '其它'];
        $where['status'] = 0;
        // 待跟进客户
        $where1['relation_type'] = 1;
        $customerlist = Record::where($where)->where($where1)->column('id');
        $customerlist1 = 0;
        if ($customerlist) {
            $whereExit['id'] = array('in', $customerlist);
            $whereExit['next_time'] = array('gt', date('Y-m-d 23:59:59'));
            $customerlist1 = Record::where($whereExit)->count();
        }
        $customer = count($customerlist) - $customerlist1;

        //待跟进合同
        $where2['relation_type'] = 3;
        $contractlist = Record::where($where)->where($where2)->column('id');
        $contractlist1 = 0;
        if ($contractlist) {
            $whereExitC['id'] = array('in', $contractlist);
            $whereExitC['next_time'] = array('gt', date('Y-m-d 23:59:59'));
            $contractlist1 = Record::where($whereExitC)->count();
        }
        $contract = count($contractlist) - $contractlist1;
        //待跟进线索
        $where3['relation_type'] = 4;
        $leadlist = Record::where($where)->where($where3)->column('id');
        $leadlist1 = 0;
        if ($leadlist) {
            $whereExitL['id'] = array('in', $leadlist);
            $whereExitL['next_time'] = array('gt', date('Y-m-d 23:59:59'));
            $leadlist1 = Record::where($whereExitL)->count();
        }
        $lead = count($leadlist) - $leadlist1;
        //待跟进联系人
        $where4['relation_type'] = 2;
        $contactslist = Record::where($where)->where($where4)->column('id');
        $contactslist1 = 0;
        if ($contactslist1) {
            $whereExitCs['id'] = array('in', $contactslist);
            $whereExitCs['next_time'] = array('gt', date('Y-m-d 23:59:59'));
            $contactslist1 = Record::where($whereExitCs)->count();
        }
        $contacts = count($contactslist) - $contactslist1;
        //待跟进商机
        $where5['relation_type'] = 5;
        $businesslist = Record::where($where)->where($where5)->column('id');
        $businesslist1 = 0;
        if ($businesslist1) {
            $whereExitB['id'] = array('in', $businesslist);
            $whereExitB['next_time'] = array('gt', date('Y-m-d 23:59:59'));
            $businesslist1 = Record::where($whereExitB)->count();
        }
        $business = count($businesslist) - $businesslist1;

        //待审核合同
        $examine = ExamineRecord::where([
            'relation_type' => ExamineRecord::CONTRACT_TYPE,
            'status' => 0,
            'check_staff_id' => $this->auth->id
        ])->count();
        //待审核回款
        $receivables = ExamineRecord::where([
            'relation_type' => ExamineRecord::RECEIVABLES_TYPE,
            'status' => 0,
            'check_staff_id' => $this->auth->id
        ])->count();
        //待回款提醒
        $receivablesPlan = ReceivablesPlan::where([
            'remind_date' => ['elt', date('Y-m-d')],
            'status' => 0,
            'owner_staff_id' => $this->auth->id
        ])->count();
        //待处理日程
        $eventOne = Event::where([
            'type' => 1,
            'status' => ['in', [0, 1]],
            'start_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
            'staff_id|owner_staff_id' => $this->auth->id,
        ])->count();
        $this->success('请求成功', [
            'customer' => $customer,
            'business' => $business,
            'contract' => $contract,
            'lead' => $lead,
            'contacts' => $contacts,
            'event_one' => $eventOne,
            'examine' => $examine,
            'receivables' => $receivables,
            'receivables_plan' => $receivablesPlan
        ]);
    }

    //待处理日程
    public function event_one()
    {
        // 待处理日程
        $eventTask = Event::where([
            'type' => 1,
            'status' => ['in', [0, 1]],
            'start_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
            'staff_id|owner_staff_id' => $this->auth->id,
        ])->order('id desc')->select();
        //标记通知已读
        Message::where([
            'relation_type' => Message::EVENT_TYPE,
            'to_staff_id' => $this->auth->id,
            'status' => 0
        ])->update(['read_time' => time(), 'status' => 1]);
        foreach ($eventTask as &$ves) {
            $ves['start_time'] = date('Y-m-d H:i', strtotime($ves['start_time']));
            $ves['end_time'] = date('Y-m-d H:i', strtotime($ves['end_time']));
        }
        $this->success('请求成功', $eventTask);
    }

    //跟进任务
    public function event_task()
    {
        // 待跟进任务
        $eventTask = Event::where([
            'type' => 2,
            'status' => ['in', [0, 1]],
            'start_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
            'staff_id' => $this->auth->id
        ])->select();
        foreach ($eventTask as &$ves) {
            $ves['start_time'] = date('Y-m-d H:i', strtotime($ves['start_time']));
            $ves['end_time'] = date('Y-m-d H:i', strtotime($ves['end_time']));
        }
        $this->success('请求成功', $eventTask);
    }


    //待审核合同
    public function examine_contract()
    {
        //待审核合同
        $ids = ExamineRecord::where([
            'relation_type' => ExamineRecord::CONTRACT_TYPE,
            'status' => 0,
            'check_staff_id' => $this->auth->id
        ])->column('relation_id');
        $contracts = ContractModel::where(['id' => ['in', $ids]])->with([
            'customer',
            'contacts',
            'ownerStaff',
            'orderStaff',
            'receivables'
        ])->order('id desc')->select();
        $contracts = collection($contracts)->toArray();
        foreach ($contracts as $k => $v) {
            if (empty($v['receivables'])) {
                $v['receivables'] = [
                    'repayment_money' => 0,
                    'be_money' => $v['money'],
                    'ratio' => 0
                ];
            } else {
                $be_money = $v['money'] - $v['receivables']['repayment_money'];
                $v['receivables'] = [
                    'repayment_money' => $v['receivables']['repayment_money'],
                    'be_money' => ($be_money > 0) ? $be_money : 0,
                    'ratio' => round($v['receivables']['repayment_money'] / $v['money'] * 100, 2)
                ];
            }
            $contracts[$k] = $v;
        }

        $this->success('请求成功', $contracts);
    }


    //待审核回款
    public function examine_receivables()
    {
        //待审核回款
        $ids = ExamineRecord::where([
            'relation_type' => ExamineRecord::RECEIVABLES_TYPE,
            'status' => 0,
            'check_staff_id' => $this->auth->id,
        ])->column('relation_id');
        $receivables = Receivables::where(['id' => ['in', $ids]])->with([
            'contract',
            'createStaff'
        ])->order('id desc')->select();

        $this->success('请求成功', $receivables);
    }


    //待回款提醒
    public function examine_receivables_plan()
    {
        //待回款提醒
        $receivablesPlan = ReceivablesPlan::where([
            'remind_date' => ['elt', date('Y-m-d')],
            'status' => 0,
            'owner_staff_id' => $this->auth->id,
        ])->order('id desc')->with(['contract', 'customer'])->select();

        $this->success('请求成功', $receivablesPlan);
    }


    //数据简报
    public function briefing()
    {
        $type = input('type', 0);//0 本人及下属 1 仅本人 2 仅下属
        $times = input('times', '');
        $times = explode(',', $times);
        if (empty($times)) {
            $this->error('参数不能为空');
        }

        $startDate=strtotime($times[0]);
        $endDate=strtotime($times[1])+86400-1;

		$where = [
			'createtime' => ['between', [$startDate, $endDate]]
		];
        $whereC = [
            'order_date' => ['between', [date('Y-m-d 00:00:00',$startDate), date('Y-m-d 23:59:59',$endDate)]]
        ];
        $whereR = [
            'return_time' => ['between', [date('Y-m-d 00:00:00',$startDate), date('Y-m-d 23:59:59',$endDate)]]
        ];
		if ($type == 1) {
			$where['owner_staff_id'] = $this->auth->id;
            $whereC['owner_staff_id'] = $this->auth->id;
            $whereR['owner_staff_id'] = $this->auth->id;
		} elseif ($type == 2) {
			$where['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
            $whereC['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
            $whereR['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
		} else {
			$where['owner_staff_id'] = ['in', Staff::getMyStaffIds()];
            $whereC['owner_staff_id'] = ['in', Staff::getMyStaffIds()];
            $whereR['owner_staff_id'] = ['in', Staff::getMyStaffIds()];
		}

		//客户 线索 联系人 合同 回款 跟进次数 处理审批
		$leads             = Leads::where($where)->count();
		$customer          = Customer::where($where)->count();
		$contacts          = Contacts::where($where)->count();
		$contract          = Contract::where([])->where($whereC)->count();
		$contract_money    = Contract::where(['check_status'=>2])->where($whereC)->sum('money');
		$receivables_money = Receivables::where(['check_status'=>2])->where($whereR)->sum('money');
		$record            = Record::where([
            'create_staff_id' => $where['owner_staff_id'],
            'createtime' => $where['createtime']
        ])->where(['follow_type' => ['neq', '其它']])->count();
        $examine = ExamineRecord::where([
            'check_staff_id' => $where['owner_staff_id'],
            'createtime' => $where['createtime']
        ])->count();
        //商机总数
        $business = Business::where($where)->count();
        //客户成交量
        $customer_complate = Customer::where($where)->where(['contract_status' => 1])->count();
        //客户未成交量
        $customer_nocomplate = Customer::where($where)->where(['contract_status' => 0])->count();
        //商机成交总数
        $business_complate = Business::where($where)->where(['contract_status' => 1])->count();
        //商机未成交总数
        $business_nocomplate = Business::where($where)->where(['contract_status' => 0])->count();
        //商机成交金额
        $business_complate_money = Business::where($where)->where(['contract_status' => 1])->sum('money');
        //商机未成交金额
        $business_nocomplate_money = Business::where($where)->where(['contract_status' => 0])->sum('money');
        $this->success('请求成功', [
            'leads' => $leads,
            'customer' => $customer,
            'contacts' => $contacts,
            'contract' => $contract,
            'contract_money' => $contract_money,
            'receivables' => $receivables_money,
            'record' => $record,
            'business' => $business,
            'examine' => $examine,
            'customer_complate' => $customer_complate,
            'customer_nocomplate' => $customer_nocomplate,
            'business_complate' => $business_complate,
            'business_nocomplate' => $business_nocomplate,
            'business_complate_money' => $business_complate_money,
            'business_nocomplate_money' => $business_nocomplate_money,
        ]);
    }


    /**
     *交易额排行
     */
    public function contractRanding()
    {
        $date = input('date', date('Y-m'));

        $type = input('type', 0);//0 本人及下属 1 仅本人 2 仅下属


        //月底
        $endDate = date('Y-m-d', strtotime('+1 month', strtotime(date($date . '-1'))) - 1);
        $where = [
            'order_date' => ['between', [$date . '-1', $endDate]],
            'check_status' => 2,
        ];

        $contracts = Contract::where($where)->group('owner_staff_id')->field('owner_staff_id,sum(money) as money')->order('money desc')->select();
        $list = [];
        foreach ($contracts as $v) {
            $list[$v['owner_staff_id']] = $v['money'];
        }
        $contracts = $list;
        $data = [];
        $staffs = Staff::getList();
        foreach ($staffs as $v) {
            if (isset($contracts[$v['id']])) {
                $data[$v['id']] = $contracts[$v['id']];
            } else {
                $data[$v['id']] = 0;
            }
        }
        arsort($data);
        $staffs = Staff::getKeyList();
        $result = [];
        $i = 1;
        $oneMoney = 0;
        if ($type == 1) {//本人
            $showStaffIds = [$this->auth->id];
        } elseif ($type == 2) {//下属
            $showStaffIds = Staff::getLowerStaffId();
        } else {//全部
            $showStaffIds = Staff::getMyStaffIds();
        }

        foreach ($data as $id => $money) {
            if ($i == 1) {
                $oneMoney = $money;
            }
            $val = $staffs[$id];
            $val['money'] = $money;
            $val['ratio'] = $oneMoney ? sprintf("%.2f", $money / $oneMoney * 100) : 0;
            $val['rank'] = $i;
            $i++;
            if (in_array($id, $showStaffIds)) {
                $result[] = $val;
            }
        }

        if (count($result) >= 10) {
            $top = array_slice($result, 0, 3);
            $bottom = array_slice($result, -3, 3);
            $middle = array_slice($result, 3, 4);
            $result = array_merge($top, $bottom, $middle);
        }


        $this->success('请求成功', $result);
    }


    //服务协议
    public function serviceContent()
    {
        $this->success('请求成功', [
            'content' => "<h1>用户服务协议</h1>",
            'name' => '青动时代',
            'logo' => ''
        ]);
    }
}
